import MIPS.Mips;

import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class Compiler {
    public static void main(String[] args) {
        Boolean isMips = false;
        Scanner scanner = new Scanner(System.in);
        String targetStr = "";
        ReadFile file = new ReadFile();
        //targetStr = file.ReadFile();
        ArrayList<String> strings = new ArrayList<>();
        strings = file.ReadFile();
        //Analyse analyse = new Analyse(targetStr);
        Analyse analyse = new Analyse(strings);
        ArrayList<Pairs> pairs = analyse.analyseTxt();
        AnalyseParse parse = new AnalyseParse(pairs);
        Node treeNode = parse.analyseTokens();
        AnalyseTable table = new AnalyseTable(treeNode);
        table.buildTable(treeNode);
        ArrayList<Pairs> errors = table.getError();
        errors.addAll(parse.getError());
        Collections.sort(errors);
        AnalyseIR analyseIR = new AnalyseIR();
        ArrayList<Quaternion> IRs = new ArrayList<>();
        ArrayList<Mips> mips = new ArrayList<>();
        ArrayList<Mips> mipsText = new ArrayList<>();
        ArrayList<Mips> mipsFunc = new ArrayList<>();
        if (errors.isEmpty()) {
            analyseIR.buildIR(treeNode);
            IRs = analyseIR.getIRs();
            AnalyseMips analyseMips = new AnalyseMips(IRs);
            analyseMips.buildMips();
            mips = analyseMips.getMips();
            mipsText = analyseMips.getMipsText();
            mipsFunc = analyseMips.getMipsFunc();
        }

        try {
            //Writer os = new FileWriter("output.txt"); 语法分析
            /*for (Pairs i : pairs) {
                os.write(i.toString());//词法分析
            }*/
            /*os.write(treeNode.toString());
            os.close();*/   //语法分析
            Writer os = new FileWriter("error.txt");
            for (Pairs i : errors) {
                os.write(i.toString());
            }
            os.close();
            Writer os1 = new FileWriter("IRS.txt");
            for (Quaternion i : IRs) {
                os1.write(i.toString());
            }
            os1.close();
            Writer os2 = new FileWriter("mips.txt");
            for (Mips i : mipsText) {
                os2.write(i.toString());
            }
            for (Mips i : mips) {
                os2.write(i.toString());
            }
            for (Mips i : mipsFunc) {
                os2.write(i.toString());
            }
            os2.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
